package com.camin.android;

import com.camin.android.db.IngredientTable;
import com.camin.android.db.RecipeIngredientTable;
import com.camin.android.db.RecipeTable;
import com.camin.android.utils.Constants;

import android.app.AlertDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;

public class RecipeActivity extends BaseActivity implements OnClickListener {

	private Context mContext;
	TableLayout tblIngredients;
	EditText etRecipeName;
	EditText etCookingTime;
	EditText etCookingInstructions;
	EditText etServingInstructions;
	Long recipeId = null;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.recipe);

		mContext = this;
		etRecipeName = (EditText) findViewById(R.id.editRecipeName);
		etCookingTime = (EditText) findViewById(R.id.editCookingTime);
		etCookingInstructions = (EditText) findViewById(R.id.editCookingInstructions);
		etServingInstructions = (EditText) findViewById(R.id.editServingInstructions);

		tblIngredients = (TableLayout) findViewById(R.id.tblIngredients);

		Bundle extras = getIntent().getExtras();
		if (extras != null) {
			recipeId = extras.getLong(Constants.RECIPE_ID);
		}

		if (recipeId != null) {
			// preload form with data
			Cursor recipeCursor = getDataHelper().getRecipeById(getDatabase(), recipeId);
			if (recipeCursor.moveToFirst()) {
				etRecipeName.setText(recipeCursor.getString(recipeCursor
						.getColumnIndex(RecipeTable.recipeName)));
				etCookingTime.setText(recipeCursor.getString(recipeCursor
						.getColumnIndex(RecipeTable.recipeCookingTime)));
				etCookingInstructions
						.setText(recipeCursor.getString(recipeCursor
								.getColumnIndex(RecipeTable.recipeCookingInstructions)));
				etServingInstructions
						.setText(recipeCursor.getString(recipeCursor
								.getColumnIndex(RecipeTable.recipeServingInstructions)));

				recipeCursor.close();
				
				Cursor recipeIngredientsCursor = getDataHelper()
						.getRecipeIngredientsById(getDatabase(), recipeId);
				
				recipeIngredientsCursor.moveToFirst();
				while (!recipeIngredientsCursor.isAfterLast()) {
					long ingredientId = recipeIngredientsCursor
							.getLong(recipeIngredientsCursor
									.getColumnIndex(RecipeIngredientTable.ingredientId));
					long ingredientQty = recipeIngredientsCursor
							.getLong(recipeIngredientsCursor
									.getColumnIndex(RecipeIngredientTable.quantity));
					String ingredientUM = recipeIngredientsCursor
							.getString(recipeIngredientsCursor
									.getColumnIndex(RecipeIngredientTable.measureUnit));
	
					if (ingredientId != -1) {
						Cursor ingredientsCursor = getDataHelper()
								.getIngredientById(getDatabase(), ingredientId);
						if (ingredientsCursor.moveToFirst()) {
							addRowToIngredientTable(ingredientQty,
									ingredientUM, ingredientsCursor);
						}
						ingredientsCursor.close();
					}
					recipeIngredientsCursor.moveToNext();
				}
				recipeIngredientsCursor.close();
			}
		}
		getDatabase().close();
		
		
		Button btnSaveRecipe = (Button) findViewById(R.id.btnSaveRecipe);
		btnSaveRecipe.setOnClickListener(new Button.OnClickListener() {
			public void onClick(View v) {
				recipeId = saveRecipe();
				Intent data = new Intent();
				data.putExtra(Constants.RECIPE_ID, recipeId);
				setResult(RESULT_OK, data);
				finish();
			}
		});

		Button btnCancelRecipe = (Button) findViewById(R.id.btnCancelRecipe);
		btnCancelRecipe.setOnClickListener(new Button.OnClickListener() {
			public void onClick(View v) {
				finish();
			}
		});

		Button btnAddIngredientRecipe = (Button) findViewById(R.id.btnAddIngredientRecipe);
		btnAddIngredientRecipe.setOnClickListener(new Button.OnClickListener() {
			public void onClick(View v) {
				Intent intent = new Intent(getBaseContext(),
						IngredientRecipeActivity.class);
				startActivityForResult(intent, 0);
			}
		});
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		long ingredientId = -1l;
		long ingredientQty = 0l;
		String ingredientUM;

		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == RESULT_OK) {
			Bundle extras = data.getExtras();
			if (extras != null) {
				ingredientId = extras.getLong(Constants.INGREDIENT_ID, -1l);
				ingredientQty = extras.getLong(Constants.INGREDIENT_QTY, 0l);
				ingredientUM = extras.getString(Constants.INGREDIENT_UM);
				if (ingredientId != -1) {
					Cursor cursor = getDataHelper().getIngredientById(getDatabase(),
							ingredientId);
					if (!checkIngredientId(ingredientId)) {
						if (cursor.moveToFirst()) {
							addRowToIngredientTable(ingredientQty,
									ingredientUM, cursor);
						}
					} else {
						cursor.moveToFirst();
						String ingredName = cursor
								.getString(cursor
										.getColumnIndex(IngredientTable.ingredientName));

						AlertDialog.Builder adb = new AlertDialog.Builder(
								mContext);
						adb.setTitle("Duplicate");
						adb.setMessage("The ingredient " + ingredName
								+ " already exists.");
						adb.setPositiveButton("Ok", null);
						adb.show();
					}
					cursor.close();
					getDatabase().close();
				}
			}
		}
	}

	/**
	 * Check if the ingredient with the id : ingredId exists in our table
	 */
	private boolean checkIngredientId(long ingredId) {
		for (int i = 0; i < tblIngredients.getChildCount(); i++) {
			TableRow row = (TableRow) tblIngredients.getChildAt(i);
			if (row.getId() == ingredId) {
				return true;
			}
		}
		return false;
	}

	/**
	 * Dynamically add a row to ingredientTable
	 * 
	 * @param ingredientQty
	 * @param cursor
	 */
	private void addRowToIngredientTable(long ingredientQty,
			String ingredientUM, Cursor cursor) {

		TableRow tr = new TableRow(this);
		tr.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,
				LayoutParams.WRAP_CONTENT));
		tr.setId(cursor.getInt(cursor.getColumnIndex(IngredientTable._ID)));

		LinearLayout linearLayout = new LinearLayout(this);
		linearLayout.setOrientation(LinearLayout.HORIZONTAL);

		// name of ingredient
		TextView tvIngredientName = new TextView(this);
		tvIngredientName.setLayoutParams(new LayoutParams(220,
				LayoutParams.WRAP_CONTENT));
		tvIngredientName.setGravity(Gravity.CENTER_VERTICAL);
		tvIngredientName.setText(cursor.getString(cursor
				.getColumnIndex(IngredientTable.ingredientName)));
		linearLayout.addView(tvIngredientName);

		// quantity for ingredient
		TextView tvIngredientQty = new TextView(this);
		tvIngredientQty.setLayoutParams(new LayoutParams(40,
				LayoutParams.WRAP_CONTENT));
		tvIngredientQty.setGravity(Gravity.CENTER_VERTICAL);
		tvIngredientQty.setText(String.valueOf(ingredientQty));
		linearLayout.addView(tvIngredientQty);

		// measure unit for ingredient
		TextView tvIngredientUM = new TextView(this);
		tvIngredientUM.setLayoutParams(new LayoutParams(40,
				LayoutParams.WRAP_CONTENT));
		tvIngredientUM.setGravity(Gravity.CENTER_VERTICAL);
		tvIngredientUM.setText(ingredientUM);
		linearLayout.addView(tvIngredientUM);

		// delete button
		ImageView btnDelete = new ImageView(this);
		btnDelete
				.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, 30));
		btnDelete.setImageResource(R.drawable.ic_menu_delete);
		btnDelete.setId(cursor.getInt(cursor
				.getColumnIndex(IngredientTable._ID)));
		btnDelete.setOnClickListener(this);

		linearLayout.addView(btnDelete);

		tr.addView(linearLayout);

		tblIngredients.addView(tr);
	}

	@Override
	public void onClick(final View v) {

		final long ingrId = v.getId();
		String ingredientName = "";
		Cursor cursor = getDataHelper().getIngredientById(getDatabase(),ingrId);
		if (cursor.moveToFirst()) {
			ingredientName = cursor.getString(cursor
					.getColumnIndex(IngredientTable.ingredientName));
		}
		
		cursor.close();
		getDatabase().close();

		AlertDialog.Builder adb = new AlertDialog.Builder(mContext);
		adb.setTitle("Delete?");
		adb.setMessage("Are you sure you want to delete " + ingredientName);
		adb.setNegativeButton("Cancel", null);
		adb.setPositiveButton("Ok", new AlertDialog.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {

				tblIngredients.removeView((View) v.getParent().getParent());
			}
		});
		adb.show();

	}

	private long saveRecipe() {
		boolean result = false;
		SQLiteDatabase db;

		ContentValues values = new ContentValues();
		values.put(RecipeTable.recipeName, etRecipeName.getText().toString());
		values.put(RecipeTable.recipeCookingTime,
				Long.valueOf(etCookingTime.getText().toString()));
		values.put(RecipeTable.recipeCookingInstructions, etCookingInstructions
				.getText().toString());
		values.put(RecipeTable.recipeServingInstructions, etServingInstructions
				.getText().toString());

		db = getDataHelper().getWritableDatabase();
		db.beginTransaction();

		if (recipeId == null) {
			recipeId = getDataHelper().insertRecipe(db, values);
		} else {
			if (getDataHelper().updateRecipe(db, values, recipeId) == 0)	{
				// if update failed force failed for saveIngredients
				recipeId = -1l;
			}
		}
		if (recipeId != -1) {
			result = saveRecipeIngredients(db, recipeId);
		}
		if (result == true) {
			db.setTransactionSuccessful();
		}
		db.endTransaction();
		getDataHelper().close();
		return recipeId;
	}

	private boolean saveRecipeIngredients(SQLiteDatabase db, long recipeId) {

		// first we delete all ingredient from this recipe
		getDataHelper().deleteRecipeIngredient(db, recipeId);

		ContentValues recipeIngredientValues = new ContentValues();

		// after removal we add all elements and the tblIngredients
		for (int i = 0; i < tblIngredients.getChildCount(); i++) {
			TableRow row = (TableRow) tblIngredients.getChildAt(i);
			LinearLayout ll = (LinearLayout) row.getChildAt(0);
			TextView tvIngredientQty = (TextView) ll.getChildAt(1);
			TextView tvIngredientUM = (TextView) ll.getChildAt(2);
			// recipe id
			recipeIngredientValues
					.put(RecipeIngredientTable.recipeId, recipeId);
			// ingredient id
			recipeIngredientValues.put(RecipeIngredientTable.ingredientId,
					row.getId());
			recipeIngredientValues.put(RecipeIngredientTable.quantity,
					Long.parseLong(tvIngredientQty.getText().toString()));
			recipeIngredientValues.put(RecipeIngredientTable.measureUnit,
					tvIngredientUM.getText().toString());

			long id = getDataHelper().insertRecipeIngredient(db,
					recipeIngredientValues);

			if (id == -1) {
				return false;
			}
		}

		return true;
	}

}
